package com.jxud.controller;

import com.jxud.Pojo.*;
import com.jxud.service.OrderService;
import com.jxud.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin(origins = "*")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 根据token 获取到当前客户的订单Controller
     *
     * @param request
     * @return
     */
    @PostMapping("/api/orders")
    public Result getOrdersByCustomerId(HttpServletRequest request, @RequestBody PageOrder pageOrder) {
        log.info("========================================获取订单列表=================================================");
        System.out.println("startTime: " + pageOrder.getStartTime());
        System.out.println("endTime: " + pageOrder.getEndTime());
        Map<String,Object> ordersByCustomerId = orderService.getOrdersByCustomerId(request,pageOrder);
        return Result.success(ordersByCustomerId);
    }

    /**
     * 获取单个不脱敏的订单
     *
     * @return
     */
    @PostMapping("/api/order/desens")
    public Result getOrderItem(@RequestBody Map<String, String> requestBody) {
        log.info("=======================================单个订单不脱敏=================================================");
        String orderId = requestBody.get("orderId");
        List<Order> data = orderService.getOrdersByIdDesens(orderId);
        return Result.success(data);
    }

    /**
     * 创建订单
     *
     * @param order
     * @return
     */
    @PostMapping("/api/order/createOrder")
    public Result createOrder(@RequestBody Order order, HttpServletRequest request) {
        log.info("========================================创建订单=================================================");

        Boolean canOrder = orderService.UserOrderEligibilityService(request);
        if(!canOrder){
            return Result.error("您的账号，存在问题请联系管理员");
        }

        log.info("创建订单：{}", order);
        String s = orderService.createOrder(order, request);
        return Result.success(s);
    }

    /**
     * 批量上传
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/api/upload")
    public Result  handleFileUpload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        log.info("========================================Excel批量上传订单=================================================");
        try (InputStream inputStream = file.getInputStream()) {
            return orderService.readExcelFile(inputStream, request);
        } catch (Exception e) {
            return Result.error("文件处理失败: " + e.getMessage());
        }
    }

    /**
     * 关闭订单
     * @param orderId
     * @return
     */
    @PostMapping("/api/orders/{orderId}/close")
    public Result closeOrder(@PathVariable("orderId") String orderId) {
        log.info("========================================关闭订单=================================================");
        log.info("关闭订单{}", orderId);
        Integer updatedRows = orderService.closeOrder(orderId);
        if (updatedRows == 1) {
            return Result.success("订单关闭成功");
        } else {
            return Result.error("当前订单状态不允许关闭");
        }
    }

    /**
     * 修改订单的状态
     * bindingResult:必须紧跟在 @Valid 注解的参数后面，否则它就“绑定”不到校验结果
     * Valid: 参数实体类的验证
     */
    @PostMapping("/api/orders/status")
    public Result updateOrderStatus(@Valid @RequestBody UpdateOrderStatus updateOrderStatus, BindingResult bindingResult, HttpServletRequest request) {
        log.info("++++++++++++++++++++++++管理员修改订订单++++++++++++++++++++++++++++++++++++++++");

        if (bindingResult.hasErrors()) {
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            return Result.error("参数错误："+errorMsg);
        }

        Result result = orderService.UpdateOrderStatus(updateOrderStatus, request);
        return result;
    }


}
